package com.carleasoft.mps.file.common.util;

import com.carleasoft.mps.utils.MinioUtils;
import com.github.tobato.fastdfs.domain.fdfs.FileInfo;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Description: 文件工具类 </p>
 * @since 2020/5/14
 * @author wangxiao
 */
@Component
public class FastdfsUtil {

    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private MinioUtils minioUtils;
    /**
     * 文件上传
     * @param multipartFile
     * @return
     * @throws Exception
     */
    public String upload(MultipartFile multipartFile) throws Exception {
        String originalFilename = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
        //上传图片
//        StorePath storePath = storageClient.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), originalFilename, null);
        List<String> upload = minioUtils.upload(new MultipartFile[]{multipartFile});
        return minioUtils.getPreviewFileUrl(upload.get(0));
    }

    /**
     * 文件上传
     * @param originalFilename
     * @param size
     * @param inputStream
     * @return
     * @throws Exception
     */
    public String upload(String originalFilename, Long size, InputStream inputStream) throws Exception {
        //上传图片
        StorePath storePath = storageClient.uploadFile(inputStream, size, originalFilename, null);
        return storePath.getFullPath();
    }

    /**
     * 文件下载
     * @param fileUrl 文件访问地址
     * @return
     */
    public byte[] download(String fileUrl) {
        StorePath storePath = StorePath.parseFromUrl(fileUrl);
        return storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
    }

    /**
     * 删除文件
     * @param fileUrl 文件访问地址
     * @return
     */
    public void deleteFile(String fileUrl) {
        storageClient.deleteFile(fileUrl);
    }

    /**
     * 查看文件信息
     * @param filePath
     * @return
     */
    public FileInfo getFileInfo(String filePath) {
        StorePath storePath = StorePath.parseFromUrl(filePath);
        FileInfo fileInfo = storageClient.queryFileInfo(storePath.getGroup(), storePath.getPath());
        return fileInfo;
    }

    /**
     * 删除文件
     * @param
     * @return
     */
    public void deleteFile(String groupName, String path) {
        storageClient.deleteFile(groupName,path);
    }
}
